import re
from django.http import HttpResponse,JsonResponse
import os
from pathlib import Path
from mysqlModel.models import data
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def upload(req):
    print(req.FILES.get('myfile').name)
    if req.method == "POST":
        #获取上传的文件，如果没有则为None
        myFile = req.FILES.get("myfile",None)
        # 获取文件流，得到具体内容
        content = myFile.read().decode('utf-8').splitlines()
        if not re.match('\w+.lic$', myFile.name):
            return JsonResponse({'status': False, 'messages': 'license文件格式错误'})

        cust_name = content[2].split('=')[1]
        version = req.POST['version']
        cpu = req.POST['cpu']
        email = req.POST['email']
        myFile.name = f'{cust_name}_{version}_{cpu}_{email}_license.lic'
        if not re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email):
            # return redirect("/")
            return JsonResponse({'status': False, 'messages': '邮箱格式错误'})

        if not myFile:
            return JsonResponse({'status': False, 'messages': '没有上传文件'})
        #将获取到的上传文件，保存到项目目录下
        BASE_DIR = Path(__file__).resolve().parent.parent
        dir_name = os.path.join(BASE_DIR,"upload")
        print()
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)
        with open(os.path.join(dir_name,myFile.name),"wb+") as f:
            for chunk in myFile.chunks():
                f.write(chunk)
        print(cust_name)
        test1 = data(name=cust_name, soft_version=version, cpu=cpu, license=myFile, email=email)
        test1.save()

        return JsonResponse({'status': True, 'messages': '上传成功！！'})

    return HttpResponse(req)